import { ref } from "vue";
import { apiResult } from "../api/axiosConfig";

type optionsType<T> = {
  params: T;
  disableInitFetch?: boolean;
};

/**
 *
 * @param service 接口异步函数
 * @param params 函数参数
 * T：回调data的泛型
 * T2：param的泛型
 */
export const useRequest = <T = any, T2 = any>(
  service: (e: T2) => Promise<apiResult<T>>,
  options: optionsType<T2>
) => {
  const { params, disableInitFetch = false } = options;
  const loading = ref(false);
  const data = ref<T>();
  const state = ref<number>();
  const message = ref<string>();
  const total = ref<number>();
  const result = ref<apiResult<T>>();
  const fetch = async () => {
    loading.value = true;
    const res: apiResult<T> = (await service(
      params
    )) as unknown as apiResult<T>;
    data.value = res.data;
    result.value = res;
    state.value = res.state;
    message.value = res.message;
    total.value = res.total;
    loading.value = false;
  };
  if (!disableInitFetch) {
    fetch();
  }

  return {
    loading,
    fetch,
    data,
    result,
    state,
    message,
    total,
  };
};
